<!--上传单张图片-->
<template>
  <div class="upload-one-img">
    <input type="file" ref="fileButton" @change="handleFileChange">
    <div class="progress" v-if="isUploading"></div>
    <img class="preview" v-if="img" :src="img" alt="">
    <div class="btn" v-else>+</div>
  </div>
</template>

<script>
  //  import fetch from '@/utils/fetch'
  import { getUpToken } from '@/api/config'
  import global from '@/utils/global'
  import EXIF from 'exif-js'

  export default {
    props: {
      limitMB: Number, // 文件大小限制单位Mb
      limitFileType: Array,
      img: {
        type: String,
        required: true
      }
    },
    components: {},
    data () {
      return {
        qiniuUrl: global.qiniuUrl,
        isUploading: false,
        token: '',
        myImg: ''
      }
    },
    mounted () {

    },
    created () {
      getUpToken().then(res => {
        this.token = res.data.token
      })
    },
    watch: {
      myImg (newVal, oldVal) {
        console.log(newVal)
        this.$emit('update:img', newVal)
      }
    },
    methods: {
      // 选择文件
//      handleFileChange () {
//        getUpToken().then(res => {
//          this.token = res.data.token
//        })
//      },
      // 处理文件
      handleFileChange () {
        let _this = this
        let file = this.$refs.fileButton.files[0]
        if (!/\/(?:jpeg|png|gif)/i.test(file.type)) {
          alert('图片格式有误')
          return
        } else if (file.size > this.limitMB * 1024 * 1024) {
          alert('图片不能大于' + this.limitMB + 'MB')
          return
        }
        _this.isUploading = true

        // 获取图片大小
        let userImgSize = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + 'MB' : ~~(file.size / 1024) + 'KB'
        console.log('用户图片 : ' + userImgSize)
        let reader = new FileReader()
        reader.onload = function () {
          let result = this.result
          let img = new Image()
          img.src = result
          // 如果图片大小小于200kb，则直接上传
          // if (result.length <= maxsize) {
          //     img = null;
          //     doUploadFile("http://jingcai-test.oss-cn-shanghai.aliyuncs.com", sendDate, file);
          //     return;
          // }
          // 图片加载完毕之后进行压缩，然后上传
          if (img.complete) {
            callback()
          } else {
            img.onload = callback
          }

          function callback () {
            let file = transmitCode(compress(img)) // 获取
            _this.upload(file)
            img = null
          }
        }
        // 读取文件内容
        reader.readAsDataURL(file)

        // 用于压缩图片的canvas
        let canvas = document.createElement('canvas')
        let ctx = canvas.getContext('2d')
        // 瓦片canvas
        let tCanvas = document.createElement('canvas')
        let tctx = tCanvas.getContext('2d')

        /**
         * 图片压缩
         * @param img
         * @returns {string}
         */
        function compress (img) {
          let Orientation
          EXIF.getData(file, function () {
            Orientation = EXIF.getTag(this, 'Orientation')
            console.log('照片方向' + Orientation)
          })
          let initSize = img.src.length
          let width = img.width
          let height = img.height

          // 如果图片大于四百万像素，计算压缩比并将大小压至400万以下
          let ratio
          if ((ratio = width * height / 4000000) > 1) {
            ratio = Math.sqrt(ratio)
            width /= ratio
            height /= ratio
          } else {
            ratio = 1
          }

          switch (Orientation) {
            case 5:
            case 6:
            case 7:
            case 8:
              canvas.width = height
              canvas.height = width
              break
            default:
              canvas.width = width
              canvas.height = height
          }

          switch (Orientation) {
            case 3:
              // 180 rotate left
              ctx.translate(width, height)
              ctx.rotate(Math.PI)
              break

            case 6:
              // 90 rotate right
              ctx.rotate(0.5 * Math.PI)
              ctx.translate(0, -height)
              break

            case 8:
              // 90 rotate left
              ctx.rotate(-0.5 * Math.PI)
              ctx.translate(-width, 0)
              break
            default:
              break
          }

          // 铺底色
          ctx.fillStyle = '#fff'
          ctx.fillRect(0, 0, canvas.width, canvas.height)

          // 如果图片像素大于100万则使用瓦片绘制
          let count
          if ((count = width * height / 1000000) > 1) {
            count = ~~(Math.sqrt(count) + 1) // 计算要分成多少块瓦片

            // 计算每块瓦片的宽和高
            let nw = ~~(width / count)
            let nh = ~~(height / count)

            tCanvas.width = nw
            tCanvas.height = nh

            for (let i = 0; i < count; i++) {
              for (let j = 0; j < count; j++) {
                tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh)

                ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh)
              }
            }
          } else {
            ctx.drawImage(img, 0, 0, width, height)
          }

          // let mpImg = new MegaPixImage(img);
          // mpImg.render(canvas, {
          //     maxWidth: 800,
          //     maxHeight: 1200,
          //     quality: 0.8,
          //     orientation: Orientation
          // });

          // 进行压缩
          let ndata = canvas.toDataURL('image/jpeg', 0.4)

          console.log('压缩前：' + initSize)
          console.log('压缩后：' + ndata.length)
          console.log('压缩率：' + ~~(100 * (initSize - ndata.length) / initSize) + '%')

          tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0
//          previewCb && previewCb(ndata)
          return ndata
        }

        /**
         * base64转二进制对象
         * @param baseStr
         * @returns {*}
         */
        function transmitCode (baseStr) {
          let text = window.atob(baseStr.split(',')[1])
          let buffer = new Uint8Array(text.length)
          for (let i = 0; i < text.length; i++) {
            buffer[i] = text.charCodeAt(i)
          }
          let blob = getBlob([buffer], file.type)

          /**
           * 获取blob对象的兼容性写法
           * @param buffer
           * @param format
           * @returns {*}
           */
          function getBlob (buffer, format) {
            try {
              return new Blob(buffer, {type: format})
            } catch (e) {
              let bb
              if (window.BlobBuilder) {
                bb = window.BlobBuilder
              } else if (window.WebKitBlobBuilder) {
                bb = window.WebKitBlobBuilder
              } else if (window.MSBlobBuilder) {
                bb = window.MSBlobBuilder
              }
              buffer.forEach(function (buf) {
                bb.append(buf)
              })
              return bb.getBlob(format)
            }
          }

          return blob
        }
      },
      // 文件上传
      upload (file) {
        let _this = this
        let formData = new FormData()
        formData.append('file', file)
        // formData.append('key', key);
        formData.append('token', this.token)
        let oReq = new XMLHttpRequest()
        // 上传进度监听
        oReq.upload.onprogress = function (e) {
          // if (e.type == 'progress') {
          //     let percent = Math.round(e.loaded / e.total * 100, 2) + '%';
          //     // console.log(percent);
          //     if (progressCb) {
          //         progressCb(percent);
          //     }
          // }
        }
        // 上传结果
        oReq.onreadystatechange = function (e) {
          if (oReq.readyState === 4) {
            if (oReq.status === 200) {
              let response = JSON.parse(oReq.response)
              console.log(response)
//                uploadCb(response)
              _this.myImg = global.domain + response.hash
              _this.isUploading = false
            } else {
              _this.isUploading = false
              alert('图片上传失败')
            }
          }
        }
        oReq.open('POST', this.qiniuUrl)
        oReq.send(formData)
      }
    }
  }
</script>

<style lang="scss">
  .upload-one-img {
    position: relative;
    width: 100px;
    height: 100px;
    border: 1px dashed #ccc;
    overflow: hidden;
    .progress {
      position: absolute;
      z-index: 2;
      top: 0;
      left: 0;
      height: 100%;
      width: 100%;
      background-color: #000;
      opacity: .4;
      text-align: center;
      &::before {
        content: "";
        box-sizing: border-box;
        position: absolute;
        top: 50%;
        left: 50%;
        margin-top: -15px;
        margin-left: -15px;
        height: 30px;
        width: 30px;
        background: transparent !important;
        border-radius: 100%;
        border: 3px solid #fff;
        border-bottom-color: transparent;
        display: inline-block;
        -webkit-animation-fill-mode: both;
        animation-fill-mode: both;
        -webkit-animation: rotate 1.5s 0s linear infinite;
        animation: rotate 1.5s 0s linear infinite;
      }

      @keyframes rotate {
        0% {
          -webkit-transform: rotate(0deg);
          transform: rotate(0deg);
        }
        50% {
          -webkit-transform: rotate(180deg);
          transform: rotate(180deg);
        }
        100% {
          -webkit-transform: rotate(360deg);
          transform: rotate(360deg);
        }
      }
    }
    & > img {
      //position: relative;
      //z-index: 1;
      //top:50%;
      //left:50%;
      //min-width: 100%;
      //min-height: 100%;
      //transform:translate(-50%,-50%);
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    input {
      position: absolute;
      top: 0;
      left: 0;
      z-index: 3;
      width: 100%;
      height: 100%;
      -webkit-appearance: none;
      opacity: 0;
    }
    .btn{
      color: #ccc;
      font-size: 50px;
      line-height: 100px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);
    }
  }

  .animated {
    -webkit-animation-duration: 2s;
    animation-duration: 2s;
    -webkit-animation-fill-mode: both;
    animation-fill-mode: both;
  }

  @-webkit-keyframes fadeIn {
    from {
      opacity: 0;
    }

    to {
      opacity: 1;
    }
  }

  @keyframes fadeIn {
    from {
      opacity: 0;
    }

    to {
      opacity: 1;
    }
  }

  .fadeIn {
    -webkit-animation-name: fadeIn;
    animation-name: fadeIn;
  }

  @-webkit-keyframes fadeOut {
    from {
      opacity: 1;
    }

    to {
      opacity: 0;
    }
  }

  @keyframes fadeOut {
    from {
      opacity: 1;
    }
    to {
      opacity: 0;
    }
  }
  .fadeOut {
    -webkit-animation-name: fadeOut;
    animation-name: fadeOut;
  }


</style>
